<template>
  <div class="login-form">
    <a-modal
      v-model:visible="isLoginDialogVisible"
      :centered="true"
      @cancel="handleClose"
      :maskClosable="false"
      :footer="null"
      :keyboard="false"
    >
      <template #title>
        <h2 class="custom-title"> 登 录 </h2>
      </template>

      <a-form
        :model="loginForm"
        :rules="loginRules"
        ref="formRef"
      >
        <a-form-item name="username">
          <a-input
            v-model:value="loginForm.username"
            placeholder="帐号"
            size="large"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="password">
          <a-input-password
            v-model:value="loginForm.password"
            placeholder="密码"
            size="large"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <div class="footer-links">
          <a @click.prevent="goToRegister">注册</a>
          <a @click.prevent="goToForgotPassword">忘记密码</a>
        </div>

        <Verify
          ref="captchaRef"
          :captchaType="captchaType"
          :mode="mode"
          @success="captchaOnSuccess"
          @error="captchaOnError"
        />

        <a-form-item>
          <a-button
            type="primary"
            size="large"
            class="login-btn"
            :loading="loginLoader"
            @click="handleLoginBtnClick"
          >
            {{ loginLoader ? '登录中...' : '登 录' }}
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue'
import type { LoginForm } from '@/types/auth'
import { useRouter } from 'vue-router'
import { setAccessToken } from '@/utils/auth'
import { useUserStoreWithOut } from '@/store/modules/user'
import { login } from '@/api/auth'
import { message } from 'ant-design-vue'

const router = useRouter()
const userStore = useUserStoreWithOut()

const isLoginDialogVisible = defineModel()
const formRef = ref<FormInstance>()
const loginLoader = ref(false)

const captchaRef = ref(null)
const captchaType = ref('blockPuzzle')
const mode = ref('pop')

const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  captchaVerification: ''
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],

  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

/**
 * 登录按钮点击事件
 */
const handleLoginBtnClick = async () => {
  if (!formRef.value) {
    return
  }

  await formRef.value?.validate()

  if (captchaRef.value) {
    captchaRef.value?.show()
  }
}

/**
 * 验证码校验成功回调
 */
const captchaOnSuccess = (res: any) => {
  loginForm.captchaVerification = res.captchaVerification
  handleLogin()
}

/**
 * 验证码校验失败回调
 */
const captchaOnError = () => {
  console.log('验证失败，请重试！')
  // message.error('验证失败，请重试！')
}

// 登录处理
const handleLogin = async () => {
  try {
    loginLoader.value = true

    const { userId, accessToken } = await login(loginForm)

    if (!userId || !accessToken) {
      return
    }

    await userStore.setUserId(userId)
    setAccessToken(accessToken)

    message.success('登录成功')
    window.location.reload()
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loginLoader.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  handleClose()
  router.push('/register')
}

// 跳转到忘记密码页面
const goToForgotPassword = () => {
  handleClose()
  router.push('/forgotPassword')
}

// 对话框关闭事件
const handleClose = () => {
  formRef.value?.resetFields()
  isLoginDialogVisible.value = false
}
</script>

<style scoped>
.custom-title {
  text-align: center;
  font-weight: bold;
  padding: 8px 0;
  cursor: default;
}

.footer-links {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #1890ff;
  text-decoration: none;
}

.input-field {
  margin-bottom: 16px;
}

.login-btn {
  width: 100%;
  height: 40px;
  font-size: 14px;
  font-weight: bold;
  border-radius: 8px;
}
</style>
